<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from "vue";
import type {
  UploadFile,
  UploadRequestHandler,
  UploadRequestOptions
} from "element-plus";
import ReCol from "@/components/ReCol";
import { createRules, updateRules } from "../utils/rule";
/** 表单字段 */
import { FormProps } from "../utils/types";
import { usePublicHooks } from "../../../hooks";

import { useManage } from "../utils/hook";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { getUploadToken, uploadImage } from "@/api/reward";


const { shoppingidList } = useManage();
/** 表单字段初始化 */
const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    title: "新增",
    /** 礼品名称 */
    name: "",
    /** 描述 */
    desc: "",
    /** 兑换积分 */
    point: 1,
    /** 礼品图片 */
    photo: "",
    /** 发货方式 */
    type: "",
    /** 剩余数量 */
    inventory: 1,
    /** 发货方式id */
    shippingid: 0
    /** 状态 */
    // enable: true
  })
});
const ruleFormRef = ref();
let fromRule = ref();
const { switchStyle } = usePublicHooks();
const newFormInline = ref(props.formInline);
function getRef() {
  return ruleFormRef.value;
}

/** 图片上传配置 */
const userAccept = ".jpg, .png, .jpeg, .webp";
/** 图片上传列表 */
const fileList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const uploadRef = ref();
/** 删除图片钩子 */
const handleRemove = (file: UploadFile) => {
  fileList.value = [];
  newFormInline.value.imgid = "";
  newFormInline.value.isUpload = 0;
};

/** 图片预览钩子 */
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const handleDownload = (file: UploadFile) => {
  console.log(file);
};
/** 添加和上传图片都会触发 */
const handleChange = async () => {
  console.log("handleChange");
  newFormInline.value.isUpload = 1;
};

/** 自定义图片上传方法 */
const handleUpload: UploadRequestHandler = async (
  options: UploadRequestOptions
) => {
  console.log("upload");
  let imgId = options.file.uid;
  newFormInline.value.imgid = imgId.toString();
  let uploadUrl = await getToken(imgId);
  let res = await uploadImage(uploadUrl, options.file);
  console.log(res);
  return res;
};

/** 获取图片上传令牌 */
const getToken = async imgId => {
  let { data } = await getUploadToken(imgId);
  console.log(data.url);
  return data.url;
};
/** 触发自定义上传方法 */
const uploadPic = () => {
  uploadRef.value.submit();
};

/** 选择表单数据验证规则类型 */
const chooseRule = () => {
  if (newFormInline.value.title === "新增") {
    fromRule.value = createRules;
  } else {
    fromRule.value = updateRules;
  }
};

onMounted(() => {
  chooseRule();
});

/** 对外暴露组件方法 */
defineExpose({ getRef, uploadPic });
</script>

<!-- ✨该表单实现了 修改和新增 两种状态表单公用 -->
<!-- 默认状态为 修改表单 -->
<!-- 仅在 newFormInline.title 的值为 新增时，显示新增表单 -->
<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="fromRule"
    label-width="82px"
    :validate-on-rule-change="false"
  >
    <el-row :gutter="30">
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="礼品名称" prop="name">
          <el-input
            v-model="newFormInline.name"
            clearable
            placeholder="请输入礼品名称"
          />
        </el-form-item>
      </re-col>

      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="描述" prop="string">
          <el-input
            v-model="newFormInline.desc"
            clearable
            placeholder="请输入礼品描述"
          />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="兑换积分" prop="point">
          <el-input
            v-model.number="newFormInline.point"
            type="number"
            clearable
            placeholder="请输入兑换积分"
          />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24" style="display: none">
        <el-form-item label="礼品图片" prop="photo">
          <el-input
            v-model="newFormInline.photo"
            clearable
            placeholder="请输入礼品图片"
          />
        </el-form-item>
      </re-col>
      <!-- 发货方式 -->
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="发货方式" prop="shippingid">
          <el-select
            v-model="newFormInline.shippingid"
            placeholder="请选择发货方式"
            class="!w-[180px]"
          >
            <el-option
              v-for="(item, index) in shoppingidList"
              :key="index"
              :label="item.name"
              :value="item.shippingid"
            />
          </el-select>
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="剩余数量" prop="inventory">
          <el-input
            v-model.number="newFormInline.inventory"
            type="number"
            clearable
            placeholder="请输入剩余数量"
          />
        </el-form-item>
      </re-col>

      <!-- 上传图片 -->
      <re-col :value="24">
        <el-form-item label="上传图片" prop="upload">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :auto-upload="false"
            :accept="userAccept"
            list-type="picture-card"
            :limit="1"
            :on-change="handleChange"
            :http-request="handleUpload"
          >
            <el-icon><Plus /></el-icon>
            <!-- 上传图片操作按钮 -->
            <template #file="{ file }">
              <div>
                <img class="object-contain" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <el-icon><Download /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </re-col>
      <!-- 图片id -->
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="图片id" prop="imgid">
          <el-input
            v-model="newFormInline.imgid"
            clearable
            placeholder="请先上传图片"
            disabled
          />
        </el-form-item>
      </re-col>
      <re-col :value="12" :xs="24" :sm="24">
        <el-form-item label="上传状态" prop="isUpload">
          <el-input v-model="newFormInline.isUpload" clearable />
        </el-form-item>
      </re-col>
    </el-row>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </el-form>
</template>
